package com.example.androidtest1;

import android.app.Activity;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidtest1.proj.util.AISearcherImp;
import com.example.androidtest1.proj.util.BinaryTree;
import com.example.androidtest1.proj.util.Searcher;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;

public class MainActivityProject extends AppCompatActivity {
    public static final String FILE_NAME = "point24"; // 保存的文件名称
    public static final String DATABASE_NAME = "test_db";
    MyDatabaseHelper dbHelper = null;
    SQLiteDatabase db = null;

    EditText editTextA, editTextB, editTextC, editTextD;
    TextView textViewSolution;
    Button buttonRand, buttonSolve, buttonSolveAll, buttonAbout, buttonExit;
    ListView listView;

    int[] arr = new int[4];

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.buttonRand:
                    genRandData();
                    break;
                case R.id.buttonSolve:
                    solveOnce();
                    break;
                case R.id.buttonSolveAll:
                    solveAll();
                    break;
                case R.id.buttonExit:
                    System.exit(0);
                    break;
                case R.id.buttonAbout:
                    Toast.makeText(MainActivityProject.this, "越来越聪明的24点小游戏", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    private void solveAll() {

        updateArr();
        //3,2,4,1
        Arrays.sort(arr);
        String keys = Arrays.toString(arr);//[1,2,3,4]
        Log.i("DB", "start querying2!");
        Cursor cursor = db.query("tb2", new String[]{"numbers", "solution"}, null, null, null, null, null);
        Set<String> sets = new TreeSet<>();
        List<String> sols = new Vector<>();
        Log.i("DB", "start querying2!");
        while (cursor.moveToNext()) {
            String numbers = cursor.getString(cursor.getColumnIndex("numbers"));
            if (numbers.equals(keys)) {
                String solution = cursor.getString(cursor.getColumnIndex("solution"));
                sets.add(solution);
            }

        }
        sols.addAll(sets);
// 否则计算后存入数据库
        if (sets.isEmpty()) {
            Set<List<String>> lists = new AISearcherImp().searchAll(arr);

            for (List<String> exp2 : lists) {
                sets.add(suffixExpressionToMid(exp2));
            }
            sols.clear();
            for (String sol : sets) {
                sols.add(sol);
                ContentValues values = new ContentValues();
                Log.i("DB", "start inserting!");
                values.put("numbers", keys);
                values.put("solution", sol);
                // 数据库执行插入命令
                db.insert("tb2", null, values);
            }
        }
        listView.setAdapter(new ArrayAdapter<String>(MainActivityProject.this,
                android.R.layout.simple_selectable_list_item, sols));
        Toast.makeText(MainActivityProject.this, "累计" + sols.size() + "组!", Toast.LENGTH_LONG).show();
    }

    private void updateArr() {
        try {
            arr[0] = Integer.parseInt(editTextA.getText().toString());
            arr[1] = Integer.parseInt(editTextB.getText().toString());
            arr[2] = Integer.parseInt(editTextC.getText().toString());
            arr[3] = Integer.parseInt(editTextD.getText().toString());
        } catch (Exception e) {
            Toast.makeText(MainActivityProject.this, "输入错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void solveOnce() {
        updateArr();
        //3,2,4,1
        Arrays.sort(arr);
        String keys = Arrays.toString(arr);//[1,2,3,4]
// 先查询数据库的结果 如果存在直接读取结果
        Log.i("DB", "start querying1!");
        Cursor cursor = db.query("tb2", new String[]{"numbers", "solution"}, null, null, null, null, null);
        boolean find = false;
        Log.i("DB", "start querying2!");
        while (cursor.moveToNext()) {
            String numbers = cursor.getString(cursor.getColumnIndex("numbers"));
            if (numbers.equals(keys)) {
                String solution = cursor.getString(cursor.getColumnIndex("solution"));
                textViewSolution.setText(solution);
                Toast.makeText(MainActivityProject.this, "读取本地数据库记录", Toast.LENGTH_SHORT).show();
                Log.i("DB", "query successfully!");
                find = true;
                break;
            }
        }
// 否则计算后存入数据库
        if (!find) {
            List<String> exp = ((Searcher) new AISearcherImp()).search(arr);
            String answer = "无解";
            if (exp != null) {
                answer = suffixExpressionToMid(exp);
            }
            textViewSolution.setText(answer);
            ContentValues values = new ContentValues();
            Log.i("DB", "start inserting!");
            values.put("numbers", keys);
            values.put("solution", answer);
            // 数据库执行插入命令
            db.insert("tb2", null, values);
            Log.i("DB", "insert successfully!");
            Toast.makeText(MainActivityProject.this, "插入数据库成功", Toast.LENGTH_SHORT).show();
        }


    }

    private String suffixExpressionToMid(List<String> exp) {
        String answer;
        BinaryTree tree = BinaryTree.createBinaryTree(exp);
        StringBuffer buffer = new StringBuffer();
        tree.midVisit(buffer);
        buffer.append("=24");
        answer = buffer.toString().replaceAll("\\*", "×").replaceAll("\\/", "÷");
        return answer;
    }

    private void genRandData() {
        for (int i = 0; i < 4; i++) {
            arr[i] = (int) (Math.random() * 9 + 1);
        }
        editTextA.setText("" + arr[0]);
        editTextB.setText("" + arr[1]);
        editTextC.setText("" + arr[2]);
        editTextD.setText("" + arr[3]);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_project);
        editTextA = findViewById(R.id.editTextA);
        editTextB = findViewById(R.id.editTextB);
        editTextC = findViewById(R.id.editTextC);
        editTextD = findViewById(R.id.editTextD);

        textViewSolution = findViewById(R.id.textViewSolution);

        buttonRand = findViewById(R.id.buttonRand);
        buttonSolve = findViewById(R.id.buttonSolve);
        buttonSolveAll = findViewById(R.id.buttonSolveAll);
        buttonAbout = findViewById(R.id.buttonAbout);
        buttonExit = findViewById(R.id.buttonExit);
        buttonRand.setOnClickListener(listener);
        buttonSolve.setOnClickListener(listener);
        buttonSolveAll.setOnClickListener(listener);
        buttonAbout.setOnClickListener(listener);
        buttonExit.setOnClickListener(listener);
        listView = (ListView) findViewById(R.id.listSolutions);

        //读取shared-preference
        Log.i("point24", "reading preference!!!");
        SharedPreferences share = super.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        editTextA.setText(share.getString("a", "0"));
        editTextB.setText(share.getString("b", "0"));
        editTextC.setText(share.getString("c", "0"));
        editTextD.setText(share.getString("d", "0"));
        textViewSolution.setText(share.getString("sol", "计算Ing,请等待"));
        Log.i("DB", "数据库创建成功");
        dbHelper = new MyDatabaseHelper(MainActivityProject.this, DATABASE_NAME, null, 1);
        db = dbHelper.getWritableDatabase();

    }

    @Override
    protected void onStop() {
        super.onStop();
        //缓存计算结果 shared-preference
        Log.i("point24", "saving preference!!!");
        SharedPreferences share = MainActivityProject.this.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit = share.edit();
        edit.putString("a", editTextA.getText().toString());
        edit.putString("b", editTextB.getText().toString());
        edit.putString("c", editTextC.getText().toString());
        edit.putString("d", editTextD.getText().toString());
        edit.putString("sol", textViewSolution.getText().toString());
        edit.commit();// 提交更新

    }
}